<?php

namespace App\Model;

use Carbon\Carbon;
use EasySwoole\EasySwoole\Logger;

class ArticlesApangModel extends BaseModel{

    protected $table = 'articles_apang';
    const STATUS_1 = 1;
    const STATUS_2 = 2;
    const STATUS_TEXT = [
        self::STATUS_2 => '<span class="el-tag el-tag--danger">下架</span>',
        self::STATUS_1 => '<span class="el-tag">上架</span>',
    ];
    protected $fillable = [
        'id','cateid','title','thumb','music_name','music','created_at','userid','title_color',
        'share','view','content','backimg','hot','lock','status','is_link','link_url'
    ];

    /**
     *  获取Admin文章列表
     * @param null $map
     * @return array
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\Option
     * @throws \EasySwoole\Mysqli\Exceptions\OrderByFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getAdminList($params = null) {
        switch ($params['sort']) {
            case 1:
                $sort = 'view';
                break;
            case 2:
                $sort = 'share';
                break;
            default:
                $sort = 'id';
                break;
        }
        if($params){
            if(isset($params['title']) && $params['title']){
                $this->db->whereLike('title','%'.$params['title'].'%');
            }
            if(isset($params['userid']) && $params['userid']){
                $this->where('userid',$params['userid']);
            }
            if(isset($params['hot']) && $params['hot'] != ''){
                $this->where('articles.hot',$params['hot']);
            }
            if(isset($params['lock']) && $params['lock'] != ''){
                $this->where('articles.lock',$params['lock']);
            }
            /**
             * Column 'created_at' in where clause is ambiguous query:
             * SELECT SQL_CALC_FOUND_ROWS articles.id,cateid,title,articles.thumb,music_name,articles.created_at,userid,articles.share,articles.view,hot,lock,c.name,a.nickname FROM articles RIGHT JOIN `categorys` as c on c.id = articles.cateid INNER JOIN `admins` as a on a.id = articles.userid WHERE created_at >= ? AND created_at <= ? ORDER BY articles.id DESC LIMIT 0, 10
             */
            if(isset($params['start'])){
                $this->where('articles.created_at',Carbon::parse($params['start'])->toDateString(),'>=');
            }
            if(isset($params['end'])){
                $this->where('articles.created_at',Carbon::parse($params['end'])->addDays(1)->toDateString(),'<=');
            }
        }
        $params['page'] = $params['page'] ?? 1;
        $this->db->join('`categorys` as c', 'c.id = '.$this->table.'.cateid','RIGHT')
            ->join('`admins` as a', 'a.id = '.$this->table.'.userid','INNER');
        $columns = 'articles.id,cateid,title,articles.thumb,music_name,articles.created_at,userid,articles.share,articles.view,articles.hot,articles.lock,c.name,a.nickname';
        return $this->select($columns)->orderBy('articles.'.$sort)->paginate($params['page']);
    }



    public function updateViewData($id,$info,$share,$userId){
        $this->db->startTransaction();
        try{
            $countModel = new CountsModel();
            $countInfo = $countModel->getCurrentDateInfo($id);
            if($countInfo){
                //判断是否有效用户
                if($share && $userId>0){
                    $countLogModel = new CountsLogModel();
                    //判断是否记录当前用户当日首次分享进入
                    if(!$countLogModel->getCurrentLogDateInfo($countInfo['id'],$userId)){
                        $countLogModel->create(['count_id'=>$countInfo['id'],'user_id'=>$userId,'created_at'=>Carbon::now()]);
                        //当前用户当日首次分享记录有效分享次数+1
                        $countModel->inc($countInfo['id'],'share_in');
                        $this->inc($id,'share');
                    };
                }
                //更新阅读量
                $countModel->inc($countInfo['id'],'view');
            }else{
                //新增
                $count = [
                    'art_id' => $id,
                    'admin_id' => $info['userid'],
                    'share_in' => $share ? 1 : 0,
                    'view' => 1,
                    'date' => date('Y-m-d',time()),
                ];
                $countModel->create($count);
            }

            //增加当前文章阅读量
            $this->inc($id,'view');
            $this->db->commit();
        }catch (\Exception $e){
            $this->db->rollback();
            Logger::getInstance()->log($e->getMessage(),'database');
        }
        return true;
    }



}
